<?php

namespace app\api\model;

use app\api\service\Compress;
use app\api\service\Uploader;
use app\api\validate\Upload;
use think\Cache;
use think\Db;
use think\Exception;
use think\Model;

/**
 * 媒体咨询表
 * @author 01
 * @email 319204520@qq.com
 * @date 2023-02-12 22:00
 */
class Media extends Model
{

    protected $name = 'jq_media';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;


    public function category()
    {
        return $this->hasMany('media_cates', 'media_id', 'id');
    }

    public function getList()
    {

        $data = request()->param();
        $listRows = $data['listRows'] ?? 10;
        $page = $data['page'] ?? 1;

        $map = [];
        // 分类筛选
        $cate_map = [];
        if (isset($data['cate_ids']) && $data['cate_ids']) {
            $cate_map['second_cateid'] = [
                'in',
                explode(',', $data['cate_ids'])
            ];
        }

        // 标题
        if (isset($data['title']) && $data['title']) {
            $map['a.title'] = [
                'like',
                '%' . $data['title'] . '%'
            ];
        }

        // 图片类型
        if (isset($data['type']) && ($data['type'] || $data['type'] == '0')) {
            $map['a.type'] = $data['type'];
        }

        // 拍摄时间
        if (isset($data['shooting_time']) && $data['shooting_time']) {
            $time = explode('~', $data['shooting_time']);
            $map['a.shooting_time'] = [
                'between',
                $time[0] . ',' . $time[1]
            ];
        }

        // 上传时间
        if (isset($data['create_time']) && $data['create_time']) {
            $time = explode('~', $data['create_time']);
            $map['a.create_time'] = [
                'between',
                strtotime($time[0] . ' 00:00:00') . ',' . strtotime($time[1] . ' 23:59:59')
            ];
        }



        // 排序
        $sort = "";
        if (isset($data['shooting_time_sort']) && $data['shooting_time_sort']) {
            $sort .= "a.shooting_time " . $data['shooting_time_sort'] . ",";
        }

        if (isset($data['create_time_sort']) && $data['create_time_sort']) {
            $sort .= "a.create_time " . $data['create_time_sort'] . ",";
        }

        // 下载次数
        if (isset($data['download_num_sort']) && $data['download_num_sort'])  {
            $sort .= "a.download_num " . $data['download_num_sort'] . ",";
        }

        if(isset($data)){

//            write_admin_log('进行搜索m'.$data);
        }

        $sort .= 'a.id desc';
        $query = $this->alias('a');
        if ($cate_map) {
            $map['b.cate_id'] = [
                'exp',
                Db::raw("IS NOT NULL")
            ];
            $cate_sql = (new MediaCates())
                ->where($cate_map)
                ->group('media_id')
                ->field('id as cate_id,media_id')
                ->buildSql();
            $query->join("$cate_sql b", 'a.id = b.media_id', 'left');
        }

        $map['a.is_deleted'] = '0';

        $list = $query->where($map)
            ->with(['category'])
            ->order($sort)
//            ->field('a.id,a.cover_image,a.title,a.file_num,a.content,a.create_time')
            ->paginate($listRows, false, [
                'page' => $page
            ])->toArray();

        $list = $this->handleData($list);
        return $list;
    }


    public function getMediaData($media_id = 0)
    {
        $detail = $this
            ->where('id', $media_id)
//            ->field('id,cover_image,title,file_num,content,create_time,shooting_time,admin_id,')
            ->find();
        $media_files_model = new MediaFiles();
        if ($detail) {
            $detail = $detail->toArray();
            $detail['cover_image'] = $media_files_model->getMediaCoverImage($detail['id']);
//            $detail['download_num'] = $media_files_model->getMediaDownloadNum($detail['id']); 
            $detail['download_num'] = $detail['download_num'] ? $detail['download_num'] : 0;
            $detail['shooting_time'] = date('Y.m.d', strtotime($detail['shooting_time']));
            $detail['file_num'] = (new MediaFiles())->getFileNum($detail['id']);
            $detail['account'] = (new Admin())->where('id', $detail['admin_id'])->column('realname')[0] ?? '';
            $detail['category'] = (new MediaCates())
                ->alias('a') 
                ->where(['a.media_id' => $media_id, 'b.status' => '1', 'b.is_delete' => '0'])
                ->join('jq_base_cate b', 'a.second_cateid = b.id', 'left')
                ->field('b.title,b.iswarn,b.id')
                ->select();  
                
            $detail['cate_ids'] = "";
            if ($detail['category']) { 
                $cate_ids = array_column($detail['category'], 'id');
                $detail['cate_ids'] = implode(',', $cate_ids);   
            }
           

            $first_file = $media_files_model->where([
                'is_deleted' => '0',
                'media_id'   => $media_id,
                'status'     => '1'
            ])->order('sort asc')->find();

            $file_size = $media_files_model->where([
                'is_deleted' => '0',
                'media_id'   => $media_id,
                'status'     => '1'
            ])->sum('file_size');
            $detail['file_type'] = $first_file['file_type'] ?? '';
            $detail['file_size'] = (new Uploader())->getFilesize($file_size ?? 0);
            $detail['file_info'] = $media_files_model->getFileInfo($detail['id']);
        }

        return $detail;
    }


    function handleData($list)
    {
        $media_files_model = new MediaFiles();
        foreach ($list['data'] as &$item) { 
            $item['download_num'] = $item['download_num'] ? $item['download_num'] : 0;

//            $item['download_num'] = (new MediaFiles())->getMediaDownloadNum($item['id']);
            $item['create_time'] = date('Y-m-d H:i:s', strtotime($item['create_time']));
            $item['cover_image'] = $media_files_model->getMediaCoverImage($item['id']);
            $item['file_num'] = (new MediaFiles())->getFileNum($item['id']);
            $item['cateids'] = "";
            if ($item['category']) {
                $item['cateids'] = implode(',', array_column($item['category'], 'second_cateid'));
                unset($item['category']);
            }
        }
        return $list;
    }

    /**
     * 更新进度以及状态
     * @author 01
     * @email 319204520@qq.com
     * @date 2023-02-13 23:43
     */
    public function update_media_progress($media_id = 0, $type = 0)
    {
        $map = [];

        $map['id'] = $media_id;
        if ($type == 1) {
            $map['compress_status'] = '1';
        } else {
            $map['status'] = '1';
        }
        $sucess_num = (new MediaFiles())->where($map)
            ->count();

        $detail = $this->get($media_id);


        $progress = $sucess_num > 0 ? intval($sucess_num / $detail['file_num'] * 100) : 0;

        if ($type == 1) {
            $update['compress_progress'] = $progress;
            if ($progress >= 100) {
                $update['compress_status'] = '1';
            }
        } else {
            $update['upload_progress'] = $progress;
            if ($progress >= 100) {
                $update['status'] = '1';
            }
        }

        if ($type == '0' && $progress >= 100 && $detail['type'] == '0') {
            $first_file = (new MediaFiles())->where(
                ['media_id' => $media_id,]
            )->order('sort asc')->find();
            $update['cover_image'] = $first_file['file_path'];
        }
        $result = $detail->save($update);
        return $result;
    }

    /**
     * 获取已上传数量
     * @author 01
     * @email 319204520@qq.com
     * @date 2023-02-15 20:53
     */
    public function getMediaFileSort($media_id = 0)
    {
        $media_num = (new MediaFiles())->where('media_id', $media_id)->count();
        return $media_num + 1;
    }


    /**
     * 更新下载数量
     * @author 01
     * @email 319204520@qq.com
     * @date 2023-02-22 20:30
     */
    public function updateDownloadNum($media_id = 0)
    {
        $map = [
            'media_id'   => $media_id,
            'is_deleted' => '0',
            'status'     => '1'
        ];
        $media_num = (new MediaFiles())->where($map)->sum('download_num');
        $this->where('id', $media_id)->update(['download_num' => $media_num]);
    }


}
